<?php
/**
 * Created by PhpStorm.
 * User: xh
 * Date: 2020/4/22
 * Time: 4:51 PM
 */

namespace weChat\model;


use think\Model;

class WeChatGlobalToken extends Model
{
    /** 获取
     * 1.pit-weChat-Serve-globalAccessToken
     * @param $accessToken
     * @param string $identity
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function info(&$accessToken,$identity='A'){
        $map = ['identity'=>$identity,'is_use'=>0];
        $info = $this->where($map)->find();
        if(empty($info)){
            return false;
        }
        if($info->expire_time <= DateTime(time())){
            return false;
        }
        $accessToken = $info->access_token;
        return true;
    }

    /** 添加记录
     * 1.pit-weChat-Serve-globalAccessToken
     * @param string $accessToken
     * @param int $expiresIn
     * @param string $identity
     * @return bool
     */
    public function add( $accessToken,$expiresIn,$identity='A'){
        $map = ['identity'=>$identity,'is_use'=>0];
        $this->where($map)->update(['is_use'=>1,'update_time'=>DateTime(time())]);
        $this->identity = $identity;
        $this->access_token = $accessToken;
        $this->expire_time = date('Y-m-d H:i:s',time()+$expiresIn);;
        return $this->save();
    }
}